import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:gluz/app/common/tabbar_indicator.dart';
import 'package:gluz/app/data/shop/shop_cart_entity.dart';

import '../controllers/cart_controller.dart';

/// 购物车页面
class CartView extends GetView<CartController> {
  const CartView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: _buildAppBar(),
      body: Column(
        children: [
          // 商家TabBar
          _buildStoreTabBar(),
          // 购物车列表
          Expanded(child: _buildCartList()),

          _buildBottomBar(),
        ],
      ),
    );
  }

  /// 构建顶部导航栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
        onPressed: controller.goBack,
      ),
      title: Text(
        '购物车',
        style: TextStyle(
          fontSize: 18.sp,
          fontWeight: FontWeight.bold,
          color: Colors.black,
        ),
      ),
      centerTitle: true,
    );
  }

  /// 构建商家TabBar
  Widget _buildStoreTabBar() {
    return Obx(() {
      if (controller.storeList.isEmpty) {
        return const SizedBox.shrink();
      }

      return Container(
        child: TabBar(
          controller: controller.tabController,
          isScrollable: true,
          indicatorColor: Colors.blue,
          indicatorWeight: 3,
          labelColor: Colors.blue,
          unselectedLabelColor: Colors.grey[600],
          labelStyle: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.bold),
          unselectedLabelStyle: TextStyle(fontSize: 14.sp),
          dividerColor: Colors.transparent,
          indicator: TabBarCustomIndicator(),
          tabs: controller.storeList.map((store) {
            return Tab(text: store);
          }).toList(),
          onTap: controller.switchStore,
        ),
      );
    });
  }

  /// 构建购物车列表
  Widget _buildCartList() {
    return Obx(() {
      final currentItems = controller.getCurrentStoreItems();

      if (currentItems.isEmpty) {
        return _buildEmptyState();
      }

      return ListView.builder(
        padding: EdgeInsets.all(16.w),
        itemCount: currentItems.length,
        itemBuilder: (context, index) {
          final item = currentItems[index];
          return _buildCartItem(item);
        },
      );
    });
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.shopping_cart_outlined,
            size: 80.sp,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16.h),
          Text(
            '购物车是空的',
            style: TextStyle(fontSize: 16.sp, color: Colors.grey[600]),
          ),
        ],
      ),
    );
  }

  /// 构建购物车商品条目
  Widget _buildCartItem(ShopCartEntity item) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      child: Slidable(
        key: ValueKey(item.id),
        endActionPane: ActionPane(
          motion: const ScrollMotion(),
          children: [
            // 移入收藏按钮
            SlidableAction(
              onPressed: (context) => controller.moveToFavorites(item.id),
              backgroundColor: Colors.orange,
              foregroundColor: Colors.white,
              icon: Icons.favorite_border,
              label: '收藏',
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8.r),
                bottomLeft: Radius.circular(8.r),
              ),
            ),
            // 删除按钮
            SlidableAction(
              onPressed: (context) => _showDeleteConfirmDialog(item),
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
              icon: Icons.delete_outline,
              label: '删除',
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(8.r),
                bottomRight: Radius.circular(8.r),
              ),
            ),
          ],
        ),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Padding(
            padding: EdgeInsets.all(10.w),
            child: InkWell(
              onTap: () => controller.toggleItemSelection(item.id),
              child: Row(
                children: [
                  // 复选框
                  Container(
                    width: 16.w,
                    height: 16.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: item.isSelected
                            ? Colors.blue
                            : Colors.grey[400]!,
                        width: 1,
                      ),
                      color: item.isSelected ? Colors.blue : Colors.transparent,
                    ),
                    child: item.isSelected
                        ? Icon(Icons.check, size: 14.sp, color: Colors.white)
                        : null,
                  ),
                  SizedBox(width: 12.w),
                  // 商品图片
                  Stack(
                    children: [
                      Container(
                        width: 80.w,
                        height: 80.w,
                        decoration: BoxDecoration(
                          color: Colors.grey,
                          borderRadius: BorderRadius.circular(8.r),
                          image: DecorationImage(
                            image: CachedNetworkImageProvider(
                              item.productImage,
                            ),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      // 运费标签
                      if (!item.isIncludePosdCost)
                        Positioned(
                          left: 0,
                          bottom: 0,
                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 8.w,
                              vertical: 2.h,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.blue,
                              borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(10),
                                topRight: Radius.circular(10),
                              ),
                            ),
                            child: Text(
                              '不含运费',
                              style: TextStyle(
                                fontSize: 8.sp,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                  SizedBox(width: 12.w),
                  // 商品信息
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 商品名称
                        Text(
                          item.productName,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.black,
                            fontWeight: FontWeight.w500,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(height: 8.h),
                        // 商品规格
                        Text(
                          item.productAttributes,
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.grey[600],
                          ),
                        ),
                        SizedBox(height: 8.h),
                        // 数量和价格
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            // 数量
                            Text(
                              '${item.quantity}件',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: Colors.grey[600],
                              ),
                            ),
                            // 价格
                            Text(
                              '¥${item.totalPrice.toStringAsFixed(2)}',
                              style: TextStyle(
                                fontSize: 16.sp,
                                color: Colors.orange,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 显示删除确认对话框
  Future<bool> _showDeleteConfirmDialog(ShopCartEntity item) {
    return Get.dialog<bool>(
      AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除商品"${item.productName}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back(result: true);
              controller.removeItem(item.id);
            },
            child: const Text('删除'),
          ),
        ],
      ),
    ).then((result) => result ?? false);
  }

  /// 构建底部操作栏
  Widget _buildBottomBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Column(
        children: [
          Obx(
            () => Row(
              children: [
                InkWell(
                  onTap: controller.toggleAllSelection,
                  child: Container(
                    // 全选
                    width: 20.w,
                    height: 20.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: controller.isAllSelected.value
                            ? Colors.blue
                            : Colors.grey[400]!,
                        width: 1,
                      ),
                      color: controller.isAllSelected.value
                          ? Colors.blue
                          : Colors.transparent,
                    ),
                    child: controller.isAllSelected.value
                        ? Icon(Icons.check, size: 14.sp, color: Colors.white)
                        : null,
                  ),
                ),
                SizedBox(width: 8.w),
                Text(
                  '全选'.tr,
                  style: TextStyle(fontSize: 12.sp, color: Colors.grey),
                ),
                SizedBox(width: 12.w),

                Text(
                  '合计'.tr,
                  style: TextStyle(fontSize: 12.sp, color: Colors.grey),
                ),
                SizedBox(width: 10.w),
                // 合计价格
                Obx(
                  () => Text(
                    '¥${controller.totalPrice.value.toStringAsFixed(2)}',
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: Colors.orange,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: 10),
          // 结算按钮
          Obx(
            () => Container(
              height: 44,
              width: double.infinity,
              child: ElevatedButton(
                onPressed: controller.selectedCount.value > 0
                    ? controller.checkout
                    : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: controller.selectedCount.value > 0
                      ? Colors.blue
                      : Colors.grey[300],
                  foregroundColor: Colors.white,
                  padding: EdgeInsets.symmetric(
                    horizontal: 24.w,
                    vertical: 12.h,
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                ),
                child: Text(
                  '结算',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
